package ru.amse.jsynchro.net.stream;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

public class LimitedInputStream extends FilterInputStream {
    protected final int BUFFER_SIZE = 1024;
    protected byte[] buffer;
    protected int bufferPos;
    protected long limit;
    
    protected LimitedInputStream(InputStream in) {
        super(in);
        buffer = new byte[BUFFER_SIZE];
    }
    
    public LimitedInputStream(InputStream in, long limit) {
        this(in);
        this.limit = limit;
        bufferPos = BUFFER_SIZE;
    }
    
    public int read() throws IOException {
//        System.out.println("in limited read limit: " + limit);
        if (limit > 0) {
            if (bufferPos == BUFFER_SIZE) {
                if (limit < BUFFER_SIZE) {
//                    System.out.println("read");
                    in.read(buffer, 0, (int) limit);
                } else {
//                    System.out.println("read hole");
                    in.read(buffer);
//                    System.out.println("after read hole");
                }
                bufferPos = 0;
            }
            limit--;
//            System.out.println("return " + buffer[bufferPos]);
            if (buffer[bufferPos] < 0) {
                return buffer[bufferPos++] + 256;
            }
            return buffer[bufferPos++];
        }
        return -1;
    }

}
